package com.cskaoyan.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.result.UserInfo;
import com.cskaoyan.shopping.constants.ShoppingRetCode;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author fan
 * @Description:
 * @since 2023/01/10 10:41
 */
@RestController
@RequestMapping("shopping")
public class CartsController {
    @Autowired
    ICartService iCartService;

    @GetMapping("carts")
    public ResponseData carts(HttpServletRequest request) {
        String userInfo = request.getHeader("user_info");
        UserInfo user = JSON.parseObject(userInfo, UserInfo.class);
        List<CartProductDto> cartListById = iCartService.getCartListById(user.getUid());
        return new ResponseUtil<>().setData(cartListById);
    }

    @PostMapping("carts")
    public ResponseData addToCart(@RequestBody CartRequest cartRequest) {
        iCartService.addToCart(cartRequest);
        return new ResponseUtil<>().setData(ShoppingRetCode.SUCCESS.getMessage());
    }

    @DeleteMapping("carts/{uid}/{pid}")
    public ResponseData deleteCartItem(@PathVariable Long uid, @PathVariable Long pid) {
        iCartService.deleteCartItem(uid, pid);
        return new ResponseUtil<>().setData(ShoppingRetCode.SUCCESS.getMessage());
    }


    @DeleteMapping("/items/{uid}")
    public ResponseData deleteCheckedItem(@PathVariable Long uid) {
        iCartService.deleteCheckedItem(uid);
        return new ResponseUtil<>().setData(ShoppingRetCode.SUCCESS.getMessage());
    }

    @PutMapping("/items")
    public ResponseData checkCartItem(@RequestBody CheckAllItemRequest checkAllItemRequest) {
        iCartService.checkAllCartItem(checkAllItemRequest);
        return new ResponseUtil<>().setData(ShoppingRetCode.SUCCESS.getMessage());
    }

    @PutMapping("/carts")
    public ResponseData carts(@RequestBody  CartRequest cartRequest ){
        iCartService.updateCartNum(cartRequest);
        return new ResponseUtil<>().setData(ShoppingRetCode.SUCCESS.getMessage());
    }
}
